<template>
  <div class="register">
    <el-dialog :visible.sync="isShow" width="600px" :show-close="true">
      <div slot="title" class="title">用户注册</div>
      <el-form :model="form" label-width="70px" ref="form" :rules="rules">
        <!-- 头像 -->
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="baseURL+'/uploads'"
            name="image"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="uploadSucess"
          >
            <img v-if="form.avatar" :src="baseURL+'/'+form.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <!-- 昵称 -->
        <el-form-item label="昵称" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>

        <!-- 手机 -->
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password></el-input>
        </el-form-item>

        <!-- 图形码 -->
        <el-form-item label="图形码" prop="code">
          <el-row>
            <el-col :span="16">
              <el-input v-model="form.code"></el-input>
            </el-col>
            <el-col :span="7" :offset="1" v-if="isflag">
              <img :src="baseURL+imgSrc" alt class="col-right" @click="getPic" />
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item label="验证码" prop="rcode">
          <el-col :span="16">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-button class="col-right" @click="getPhoneCode" :disabled="codeTime!=5">
              获取用户验码
              <span v-if="codeTime !=5">({{ codeTime }}s)</span>
            </el-button>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="updetaFrom">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPhoneCodeApi, registerUser } from "@/api/register.js";
export default {
  data() {
    return {
      baseURL: process.env.VUE_APP_URL,
      isShow: false,
      imgSrc: "/captcha?type=sendsms",
      isflag: true,
      codeTime: 5,
      form: {
        avatar: "", //是	string	头像地址
        username: "", //是	string	用户名
        email: "", //是	string	邮箱
        phone: "", //是	string	手机号
        password: "", //是	string	密码
        code: "", //是	string	验证码
        rcode: "", //短信验证码
      },
      rules: {
        avatar: [{ required: true, message: "请上传头像", trigger: "change" }],
        username: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          { min: 6, max: 16, message: "请输入6-16位的用户名", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              let _reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的邮箱"));
              }
            },
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              let _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的手机号码"));
              }
            },
            trigger: "change",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        code: [
          { required: true, message: "请输入图片验证码", trigger: "blur" },
          { min: 4, max: 4, message: "请输入4位数的验证码", trigger: "blur" },
        ],
        rcode: [{ required: true, message: "请输入", trigger: "blur" },],
      },
    };
  },
  methods: {
    //上传之前的回调函数
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG或PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //   上传成功后的回调函数
    uploadSucess(res) {
      console.log(res);
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField("avatar", (error) => {
        window.console.log("错误信息：", error);
      });
    },
    // 提交按钮
    updetaFrom() {
      this.$refs.form.validate((result) => {
        if (!result) {
          this.$message.error("验证失败，请检查");
        } else {
          // this.$message.success("验证成功");
          registerUser(this.form)
            .then(() => {
              this.$message.success("恭喜注册成功");
              this.isShow = false;
            })
            .catch((err) => {
              console.log(err);
              // this.$message.error(err);
            });
        }
      });
    },
    // 获取图片
    getPic() {
      this.isflag = false;
      this.$nextTick(() => {
        this.isflag = true;
      });
    },
    // 获取手机验证码
    getPhoneCode() {
      let num = 0;
      this.$refs.form.validateField(["phone", "code"], (errorMessage) => {
        if (errorMessage.length == 0) {
          num++;
        }
      });
      if (num == 2) {
        // this.$message.success('验证成功')
        // 设置定时器防止用户一直点
        this.codeTime--;
        let timeID = setInterval(() => {
          this.codeTime--;
          if (this.codeTime == 0) {
            clearInterval(timeID);
            this.codeTime = 5;
            this.getPic();
          }
        }, 1000);

        getPhoneCodeApi({
          code: this.form.code,
          phone: this.form.phone,
        })
          .then((res) => {
            this.$message.success(res.data.data.captcha + "");
          })
          .catch((err) => {
            console.log(err);
            // this.$message.error(err);
          });
      } else {
        this.$message.error("验证失败");
      }
    },
  },
  watch: {
    isShow(newVal) {
      if (!newVal) {
        this.$refs.form.resetFields();
      }
    },
  },
};
</script>

<style lang="less">
.register {
  .title {
    height: 53px;
    background: linear-gradient(#1493fa 28%, #01c6fa 96%);
    line-height: 53px;
    text-align: center;
    color: #fff;
  }
  .el-dialog__header {
    padding: 0px;
  }
  .avatar-uploader {
    text-align: center;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .col-right {
    width: 100%;
    height: 40px;
  }
}
</style>